#include "NetRequest.h"

#include "HttpHeader.h"

#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QEventLoop>
#include <QFile>

QByteArray NetRequest::gAccessResult(QNetworkAccessManager *manager, const QString &url, const Header &refer, const QByteArray &array){
    QNetworkReply * reply;
    if(array.isEmpty()){
        reply = gAccessReply(manager,url,refer);
        int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        if(status == 302 || status == 301){
            QString url = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString();
            reply->deleteLater();
            return gAccessResult(manager,url,refer);
        }
    }else{
        reply = gAccessReply(manager,url,refer,array);
    }
    QByteArray result = reply->readAll();
    reply->deleteLater();
    return result;
}

QNetworkReply * NetRequest::gAccessReply(QNetworkAccessManager *manager, const QString & url, const Header &refer, const QByteArray & array){
    QNetworkRequest logrequest;
    QNetworkReply * reply;
    QEventLoop loop;
    QObject::connect(manager,SIGNAL(finished(QNetworkReply*)),&loop,SLOT(quit()));
    logrequest.setUrl(QUrl(url));
    if(array.isEmpty())
        logrequest.setRawHeader("Content-Type","text/html;charset=UTF-8");
    else
        logrequest.setRawHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");//必须为这种content
    logrequest.setRawHeader("Accept","text/html,application/xhtml+xml,*/*");
    logrequest.setRawHeader("Connection","keep-alive");
    if(!refer.isEmpty()){
        for(Header::const_iterator it = refer.begin(); it != refer.end(); ++it){
            logrequest.setRawHeader(it.key().toUtf8(),it.value().toUtf8());
        }
    }
    logrequest.setRawHeader("User-Agent",HTTP_USER_AGENT);
    if(array.isEmpty())
        reply = manager->get(logrequest);
    else
        reply = manager->post(logrequest,array);
    loop.exec();
    QObject::disconnect(manager,SIGNAL(finished(QNetworkReply*)),&loop,SLOT(quit()));
    return reply;
}

bool NetRequest::downFile(const QString &url,const QString &absolutePathAndName){
    QFile file(absolutePathAndName);
    if(file.exists()){
        return true;
    } else {
        if(!file.open(QIODevice::WriteOnly)){
            return false;
        }else{
            QNetworkAccessManager manager;
            QByteArray result = gAccessResult(&manager,url);
            file.write(result);
            file.close();
            return true;
        }
    }
}
